import './Login.less'
import { useAuth } from '@/utils/auth'
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { $api } from '@/http/api'

const Login = () => {
  const navigate = useNavigate()
  const { signIn, setNewSignUp } = useAuth()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const login = () => {
    console.log(username, password)
    $api.user
      .login({
        username,
        password
      })
      .then((r) => {
        if (r.code === 200) {
          signIn(
            username,
            r.data.role,
            r.data.token,
            r.data.role === 2
              ? {
                  restaurantId: r.data?.restaurant_list?.at(0)?.id
                }
              : {}
          )
          setNewSignUp(false)
          //TODO select identity
          navigate('/')
        }
      })
  }
  const register = () => {
    navigate('/register')
  }

  const onUsernameChange = (e) => {
    setUsername(e.target.value)
  }

  const onPasswordChange = (e) => {
    setPassword(e.target.value)
  }

  // get image from assets by name
  const getImage = (imageName) => {
    return require(`@/assets/images/${imageName}`)
  }

  return (
    <div className="login">
      {/* avatar area */}
      <div className="avatar">
        <img src={getImage('avatar.jpg')} alt="avatar" />
      </div>
      {/* login input area */}
      <div className="login-box w-5/6 md:w-[30%]">
        <input
          type="text"
          placeholder="Please input your username/email"
          onChange={onUsernameChange}
        />
        <input
          type="password"
          placeholder="Please input your password"
          onChange={onPasswordChange}
        />
        {/* login button */}
        <div className="flex justify-between">
          <div className="btn-up" type="primary" onClick={register}>
            Sign Up
          </div>
          <div className="btn" type="primary" onClick={login}>
            Sign In
          </div>
        </div>
      </div>
    </div>
  )
}

export default Login
